package org.dreamwork.jasmine2.web.controls.chart.settings.template;

import org.dreamwork.jasmine2.template.impl.XMLTemplateParser;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2010-5-12
 * Time: 10:29:38
 */
public abstract class ChartTemplateParser extends XMLTemplateParser {
    protected abstract String getXSDPath ();

    @Override
    public boolean validateTemplate (String content) {
        try {
            parse (content);
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Source source = new StreamSource (getClass ().getResourceAsStream(getXSDPath ()));
            Schema schema = factory.newSchema (source);
            source = new DOMSource (root);
            schema.newValidator ().validate (source);
            return true;
        } catch (SAXException ex) {
            throw new RuntimeException (ex.getMessage ());
        } catch (Exception ex) {
            return false;
        }
    }

    @Override
    public Element parse (String content) {
        if (root != null) return root;
        content = content.trim ();
        if (!content.startsWith ("<settings>")) {
            int pos = content.indexOf (">");
            int last = content.lastIndexOf ("<");
            content = content.substring (pos + 1, last);
            content = "<settings>" + content + "</settings>";
        }
        return super.parse (content);
    }
}